import type { Component } from "vue";

type WithRoute = {
  id: string;
  title: string;
  icon: Component;
  routeName: string;
  subMenu?: never; // 不能有 subMenu
};

type WithSubMenu = {
  id: string;
  title: string;
  icon: Component;
  subMenu: Array<MenuItem>;
  routeName?: never; // 不能有 routeName
};

export type MenuItem = WithRoute | WithSubMenu;

export type SelectItem = Omit<MenuItem, "subMenu" | "id" | "icon">;

export type MenuMapping = { [key: string]: Record<string, string> };

export const getMenuMapping = (
  menuArr: MenuItem[],
  keyName: "id" | "routeName",
  valueName: "id" | "routeName"
) => {
  const map: MenuMapping = {};
  const traverse = (items: MenuItem[]) => {
    for (const item of items) {
      const key = item[keyName];
      if (key && item.routeName) {
        map[key] = { title: item.title };
        map[key][valueName] = item[valueName] as string;
      }
      if (Array.isArray(item.subMenu) && item.subMenu.length > 0) {
        traverse(item.subMenu);
      }
    }
  };

  traverse(menuArr);
  return map;
};
